package net.documentshare.utils.doc;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

public class PdfToImageUtil {
	public static void pdfToImage(String pdfFile, String outPath, int page) {
		pdfToImage(pdfFile, outPath, page);
	}

	public static void pdfToImage(File pdfFile, String outPath, int page) {
		pdfToImage(pdfFile, outPath, page, 0.2f);
	}

	public static void pdfToImage(File pdfFile, String outPath, int page, float scale) {
		if (pdfFile != null) {
			Document document = new Document();
			try {
				document.setFile(pdfFile.getAbsolutePath());
			} catch (Exception ex) {
			}
			// save page caputres to file.
			float rotation = 0f;
			BufferedImage image = (BufferedImage) document.getPageImage(page, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale);
			RenderedImage rendImage = image;
			// capture the page image to file
			try {
				File file = new File(outPath + File.separator + page + ".jpg");
				ImageIO.write(rendImage, "jpg", file);
			} catch (IOException e) {
				e.printStackTrace();
			}
			image.flush();
			// clean up resources
			document.dispose();
		}
	}
}
